//	Problem 061: Cyclical figurate numbers

package main

import (
	"fmt"
)

func p061() {
	data := [][]int{}
	for i := 0; i < 6; i++ {
		data = append(data, []int{})
	}
	for n := 18; n < 142; n++ {
		if p := n * (n + 1) / 2; p > 1000 && p < 10000 {
			data[0] = append(data[0], p)
		}
		if p := n * n; p > 1000 && p < 10000 {
			data[1] = append(data[1], p)
		}
		if p := n * (3*n - 1) / 2; p > 1000 && p < 10000 {
			data[2] = append(data[2], p)
		}
		if p := n * (2*n - 1); p > 1000 && p < 10000 {
			data[3] = append(data[3], p)
		}
		if p := n * (5*n - 3) / 2; p > 1000 && p < 10000 {
			data[4] = append(data[4], p)
		}
		if p := n * (3*n - 2); p > 1000 && p < 10000 {
			data[5] = append(data[5], p)
		}
	}
	// the last row has the least elements.
	for _, c := range data[5] {
		trace061(c, c, c, 31, data)
	}
}

func trace061(start, current, sum, rowMap int, data [][]int) {
	if current/100 < 10 || current%100 < 10 {
		return
	}
	for i := 0; i < 5; i++ {
		r := 1 << i
		if rowMap&r == 0 {
			continue
		}
		for _, b := range data[i] {
			if b/100 == current%100 {
				if rowMap-r == 0 {
					if b%100 == start/100 {
						fmt.Println("Problem 061:", sum+b)
					}
				} else {
					trace061(start, b, sum+b, rowMap-r, data)
				}
			}
		}
	}
}
